package com.sanmina.tms.server;

import com.sanmina.tms.dao.TrainCourseMapper;
import com.sanmina.tms.domain.TrainCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by abely on 16-5-5.
 */
@Service
public class TrainCourseServer {

    @Resource
    TrainCourseMapper trainCourseMapper;

    public List<TrainCourse> getAllTrainCourse(int start, int limit) {
        return trainCourseMapper.findAllCourse(start, limit);
    }

    public List<TrainCourse> getAllTrainCourse() {

        return trainCourseMapper.findAllCourse();
    }

    public String generateCourseId(String courseClassic) {
        List<TrainCourse> courses = trainCourseMapper.findCourseByCourseClassic(courseClassic);

        String prifix = courseClassic.substring(0,1);
        int targetId = 0;
        int index = 0;
        String code;
        if(courses.size()!=0){
            for (int i = 0; i < courses.size(); i++) {
                String courseId = courses.get(i).getCourseId().substring(1, courses.get(i).getCourseId().length());
                if (i == 0 || (i + 1) == courses.size()) {
                    targetId = Integer.valueOf(courseId);
                    index = i;
                    continue;
                } else {
                    if ((Integer.valueOf(courseId) - targetId) == 1) {
                        targetId = Integer.valueOf(courseId);
                        continue;
                    } else {
                        index = i - 1;
                        break;
                    }
                }
            }
            int temp = Integer.parseInt(courses.get(index).getCourseId().substring(1, courses.get(index).getCourseId().length())) + 1;
            code = temp < 999 ? (temp < 10 ? ("00" + temp) : (temp < 100 ? "0" + temp : "" + temp)) : "" + temp;
        }else{
            code="001";
        }

        return prifix + code;
    }


    public void addTrainCourse(TrainCourse trainCourse){
        trainCourseMapper.insert(trainCourse);
    }
}
